package io.lvdaxian.middleware.db.router.config;

import io.lvdaxian.middleware.db.router.DBRouterConfig;
import io.lvdaxian.middleware.db.router.dynamic.DynamicDataSource;
import io.lvdaxian.middleware.db.router.util.PropertyUtil;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 数据源 自动装配的配置文件
 *
 * @author lihh
 */
@Configuration
public class DataSourceAutoConfig implements EnvironmentAware {
  
  private final Map<String, Map<String, Object>> dataSourceMap = new HashMap<>();
  
  private int dbCount;  //分库数
  private int tbCount;  //分表数
  
  /**
   * db router 配置文件
   *
   * @return 返回 db router config
   * @author lihh
   */
  @Bean
  public DBRouterConfig dbRouterConfig() {
    return new DBRouterConfig(dbCount, tbCount);
  }
  
  /**
   * 从 这里 返回数据源
   *
   * @return 返回数据源
   * @author lihh
   */
  @Bean
  public DataSource dataSource() {
    // 创建数据源
    Map<Object, Object> targetDataSources = new HashMap<>();
    for (String dbInfo : dataSourceMap.keySet()) {
      // 从 这里 拿到 db信息
      Map<String, Object> objMap = dataSourceMap.get(dbInfo);
      // 从 这里 构建 dataSources
      targetDataSources.put(dbInfo, new DriverManagerDataSource(objMap.get("url").toString(), objMap.get("username").toString(), objMap.get("password").toString()));
    }
    // 设置数据源
    DynamicDataSource dynamicDataSource = new DynamicDataSource();
    dynamicDataSource.setTargetDataSources(targetDataSources);
    return dynamicDataSource;
  }
  
  /**
   * router:
   * jdbc:
   * datasource:
   * dbCount: 2
   * tbCount: 4
   * list: db01,db02
   * db01:
   * driver-class-name: com.mysql.jdbc.Driver
   * url: jdbc:mysql://127.0.0.1:3306/bugstack_01?useUnicode=true
   * username: root
   * password: 123456
   * db02:
   * driver-class-name: com.mysql.jdbc.Driver
   * url: jdbc:mysql://127.0.0.1:3306/bugstack_02?useUnicode=true
   * username: root
   * password: 123456
   */
  @Override
  public void setEnvironment(Environment environment) {
    String prefix = "router.jdbc.datasource.";
    
    dbCount = Integer.parseInt(Objects.requireNonNull(environment.getProperty(prefix + "dbCount")));
    tbCount = Integer.parseInt(Objects.requireNonNull(environment.getProperty(prefix + "tbCount")));
    
    // 这是 数据源集合
    String dataSources = environment.getProperty(prefix + "list");
    // 数据源 不为 null
    if (dataSources != null) {
      // 这里通过 逗号 分割拿到信息
      for (String dbInfo : dataSources.split(",")) {
        // 这里 拿到环境配置中 属性 构建一个集合
        Map<String, Object> dataSourceProps = PropertyUtil.handle(environment, prefix + dbInfo, Map.class);
        dataSourceMap.put(dbInfo, dataSourceProps);
      }
    }
  }
}
